package com.qianfeng.smartdevice.websocket.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.HashMultimap;
import com.qianfeng.smartdevice.event.HumitureCheckEvent;
import com.qianfeng.smartdevice.event.PowerCommandEvent;
import com.qianfeng.smartdevice.pojo.SysHumiture;
import com.qianfeng.smartdevice.service.SysHumitureService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.util.Date;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;

/**
 * Created by wenka on 2022/3/28 20:45
 *
 * @author wenkaixin
 * @version 1.0
 * @since 1.0
 */
@Component
public class HumitureCommandHandler extends BaseCommandHandler {
    //创建一个value是集合的map
    HashMultimap<String,Double> hashMultimap=HashMultimap.create();
    private ObjectMapper objectMapper;
    private SysHumitureService service;

    @Autowired
    public void setService(SysHumitureService service) {
        this.service = service;
    }

    @Autowired
    public void setObjectMapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        CompletableFuture.runAsync(()->{
            try {
                super.handleTextMessage(session, message);
                System.out.println("单独处理温湿度数据");
                String deviceKey = (String) session.getAttributes().get("deviceKey");
                //数据，是一个json格式
                String payload = message.getPayload();
                Map map = objectMapper.readValue(payload, Map.class);
                SysHumiture sysHumiture = new SysHumiture();
                sysHumiture.setDeviceId(deviceKey);
                sysHumiture.setUploadTime(new Date());
                sysHumiture.setHumidity((Double) map.get("humidity"));
                //温度，是华氏温度
                double temperature = (double) map.get("temperature");
                //转成摄氏度
                double sheshi = (temperature - 32) / 1.8;
                sysHumiture.setTemperature(sheshi);
                service.addSysHumiture(sysHumiture);
                //我想拿最近一段时间的数据进行判断，如果平均值高于某个阈值 我就触发什么情况，低于什么阈值我就触发什么情况
                //比如我现在想简单的在定义一个功能，温度高于28°打开一个指定的设备，低于28°关闭设备
                //保存当前的温度
                hashMultimap.put(deviceKey,sheshi);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });


    }
    public void onEvent(HumitureCheckEvent event){
        System.out.println("计算温湿度平均值的任务开始了");
        //获取最近一个循环周期内的温度的平均值，然后进行计算，超出某个值就做一些事情
        //最近的数据保存在什么地方，比如我们可以保存在一个map中，在这里从map中取出来，然后计算平均值
        //拿到所有的key
        Set<String> keySet = hashMultimap.keySet();
        //key就是每一个温湿度传感器的id
        for (String key : keySet) {
            //获取并移除map中指定的数据，因为数据本次使用之后就没了
            Set<Double> doubles = hashMultimap.removeAll(key);
            //orelse就是如果不能的到结果就使用orelse，相当于if else中的else
            double avg = doubles.stream().mapToDouble(Double::doubleValue).average().orElse(0d);
            if (avg>=28){
                //开风扇
                System.out.println("开风扇");
                getContext().publishEvent(new PowerCommandEvent("1234567890", "0"));
            }else {
                //关风扇
                getContext().publishEvent(new PowerCommandEvent("1234567890", "1"));
            }
        }
    }
}
